<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="168px">
      <el-form-item label="单据号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入单据号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="门店" prop="shopId">
        <el-select
          v-model="queryParams.shopId"
          placeholder="全部"
          clearable
          :style="{width: '100%'}">
          <el-option
            v-for="(item, index) in shopList"
            :key="index"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="客户" prop="customerName">
        <el-select v-model="queryParams.customerName" placeholder="全部" clearable :style="{width: '100%'}">
          <el-option v-for="(item, index) in customer" :key="index" :label="item.name"
                     :value="item.id" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="仓库" prop="scName">
        <el-select v-model="queryParams.scName" placeholder="全部" clearable :style="{width: '100%'}">
          <el-option v-for="(item, index) in ck" :key="index" :label="item.name"
                     :value="item.id" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="销售员" prop="salerName">
        <el-select v-model="queryParams.salerName" placeholder="全部" clearable :style="{width: '100%'}">
          <el-option v-for="(item, index) in user" :key="index" :label="item.userName"
                     :value="item.userId" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="销售订单号" prop="saleOrderId">
        <el-input
          v-model="queryParams.saleOrderId"
          placeholder="请输入销售订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="操作人" prop="createBy">
        <el-select v-model="queryParams.createBy" placeholder="全部" clearable :style="{width: '100%'}">
          <el-option v-for="(item, index) in user" :key="index" :label="item.userName"
                     :value="item.userId" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="操作时间" prop="createTime">
        <el-date-picker clearable
                        v-model="queryParams.createMinTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        :style="{width: '30%'}">
        </el-date-picker>
        至
        <el-date-picker clearable
                        v-model="queryParams.createMaxTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        :style="{width: '30%'}">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="审核人" prop="approveBy">
        <el-select v-model="queryParams.approveBy" placeholder="全部" clearable :style="{width: '100%'}">
          <el-option v-for="(item, index) in user" :key="index" :label="item.userName"
                     :value="item.userId" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审核时间" prop="approveTime">
        <el-date-picker clearable
                        v-model="queryParams.approveMinTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        :style="{width: '30%'}">
        </el-date-picker>
        至
        <el-date-picker clearable
                        v-model="queryParams.approveMaxTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        :style="{width: '30%'}">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="全部" clearable :style="{width: '100%'}">
          <el-option label="待审核" value="0" ></el-option>
          <el-option label="审核通过" value="3" ></el-option>
          <el-option label="审核拒绝" value="6" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="结算状态" prop="settleStatus">
        <el-select v-model="queryParams.settleStatus" placeholder="全部" clearable :style="{width: '100%'}">
          <el-option label="未结算" value="0" ></el-option>
          <el-option label="结算中" value="1" ></el-option>
          <el-option label="已结算" value="2" ></el-option>
          <el-option label="无需结算" value="6" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:order:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:order:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:order:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sheetList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="单据号" align="left" prop="code" width="170" show-overflow-tooltip/>
      <el-table-column label="门店名称" align="left" prop="shopName" />
      <el-table-column label="客户名称" align="left" prop="customerName" />
      <el-table-column label="销售员" align="left" prop="salerName" width="100"/>
      <el-table-column label="单据总金额" align="right" prop="totalAmount" width="100">
        <template slot-scope="scope">
          <span>{{ Number(scope.row.totalAmount).toLocaleString() }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品数量" align="right" prop="totalNum" />
      <el-table-column label="操作时间" align="left" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="left" prop="createBy" width="100"/>
      <el-table-column label="状态" align="left" prop="status" >
        <template slot-scope="scope">
          <span>{{ scope.row.status == 0 ? "待审核" : scope.row.status == 3 ? "审核成功" : "审核拒绝"}}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核时间" align="left" prop="approveTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approveTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核人" align="left" prop="approveBy" width="100"/>
      <el-table-column label="结算状态" align="center" prop="settleStatus" >
        <template slot-scope="scope">
          <span v-if="scope.row.settleStatus == 0">未结算</span>
          <span v-if="scope.row.settleStatus == 1">结算中</span>
          <span v-if="scope.row.settleStatus == 2">已结算</span>
          <span v-if="scope.row.settleStatus == 6">无需结算</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="left" prop="description" />
      <el-table-column label="销售订单号" align="center" prop="saleOrderId" width="200"/>
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width" width="220" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="selectOrder(scope.row)"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:order:edit']"
            v-if="scope.row.status != 3"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-finished"
            @click="statusUpdate(scope.row)"
            v-if="scope.row.status != 3"
          >审批</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:order:remove']"
            v-if="scope.row.status != 3"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 查看按钮 -->
    <el-dialog id="printableArea" :title="title" :visible.sync="open" width="1000px" append-to-body>
      <div style="border: 1px gainsboro solid;padding: 10px 10px 10px 30px">
        <div style="display: inline-block;width: 300px;"><p>门店：{{ this.form.shopName }}</p></div>
        <div style="display: inline-block;width: 300px;"><p>客户：{{ this.form.customerName }}</p></div>
        <div style="display: inline-block;width: 300px;"><p>销售员：{{ this.form.salerName }}</p></div>
        <br>
        <div style="display: inline-block;width: 300px;" v-if="this.form.paymentDate"><p>付款日期：{{ parseTime(this.form.paymentDate, '{y}-{m}-{d}') }}</p></div>
        <br>
        <div style="display: inline-block;width: 300px;"><p>状态：<span :style="{color: statusColor}">{{ this.form.status==0 ? '待审核' : (this.form.status==3 ? '审核通过' : '审核拒绝') }}</span></p></div>
        <br>
        <div style="display: inline-block;width: 300px;"><p>操作人：{{ this.form.createBy }}</p></div>
        <div style="display: inline-block;width: 300px;"><p>操作时间：{{ parseTime(this.form.createTime, '{y}-{m}-{d}') }}</p></div>
        <br>
        <div style="display: inline-block;width: 300px;" v-if="this.form.approveBy"><p>审核人：{{ this.form.approveBy }}</p></div>
        <div style="display: inline-block;width: 300px;" v-if="this.form.approveTime"><p>审核时间：{{ parseTime(this.form.approveTime, '{y}-{m}-{d}') }}</p></div>
      </div>
      <div style="border: 1px gainsboro solid;margin-top: 5px">
        <el-table v-loading="loading" :data="this.tblSaleOutSheetDetailList" @selection-change="handleSelectionChange">
          <el-table-column label="商品编号" align="left" prop="baseDataProduct.code" width="100px" show-overflow-tooltip/>
          <el-table-column label="商品名称" align="left" prop="baseDataProduct.name" width="100px"/>
          <el-table-column label="单位" align="left" prop="baseDataProduct.unit" width="100px"/>
          <el-table-column label="规格" align="left" prop="baseDataProduct.spec" width="100px"/>
          <el-table-column label="商品类目" align="left" prop="baseDataProduct.baseDataProductCategory.name" width="100px"/>
          <el-table-column label="商品品牌" align="left" prop="baseDataProduct.baseDataProductBrand.name" width="100px"/>
          <el-table-column label="销售数量" align="left" prop="saleOrderNum" />
          <el-table-column label="出库数量" align="left" prop="orderNum" width="100"/>
          <el-table-column label="备注" align="left" prop="description" width="100px"/>
        </el-table>
      </div>
      <div style="border: 1px gainsboro solid;margin-top: 5px;padding: 10px;text-align: right">
        <label >备注： </label>
        <textarea style="width: 90%;height: 50px;margin-top: 10px;margin-left: 10px;margin-bottom: 10px;border-radius: 5px;vertical-align:middle;border: 1px gainsboro solid" v-model="this.form.description" disabled/>
      </div>

      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="handlePrint()" v-if="this.title == '查看'">打 印</el-button>
        <el-button type="success" @click="submitForm(3)" v-if="this.title == '审批'">审批通过</el-button>
        <el-button type="danger" @click="submitForm(6)" v-if="this.title == '审批'&&this.form.status!=6">审批拒绝</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 拒绝原因 -->
    <el-dialog :title="title" :visible.sync="refuseOpen" width="500px" append-to-body>
      <el-form ref="refuseForm" :model="refuseForm" :rules="refuseRules" label-width="80px">
        <el-form-item label="拒绝原因" prop="reason">
          <el-input type="textarea" v-model="refuseForm.reason" placeholder="请输入拒绝原因" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="refuseSubmit">确 定</el-button>
        <el-button @click="statusCancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listSheet, getSheet, delSheet, addSheet, updateSheet } from "@/api/system/outsheet";
import { listCustomerSettleFeeSheet, addCustomerSettleFeeSheet } from "@/api/system/CustomerSettleFeeSheet";
import {customer, center, getOrder } from "@/api/system/order";
import { listUser } from "@/api/system/user";
import {parseTime} from "../../../utils/ruoyi";
import {listStock} from "@/api/system/stock";
import { listLog, addLog } from "@/api/system/log";
import { isDelivery } from "@/api/system/TblLogisticsSheet";
import {listShop} from "../../../api/system/Shop";

export default {
  name: "Sheet",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedTblSaleOutSheetDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 销售出库单表格数据
      sheetList: [],
      // 销售出库单详情表格数据
      tblSaleOutSheetDetailList: [],
      // 仓库下拉框
      ck: [],
      // 用户(审核人、操作人、销售员)下拉框
      user: [],
      // 客户下拉框
      customer: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //拒绝原因弹窗
      refuseOpen:false,
      //弹窗状态颜色
      statusColor:"rgb(100, 100, 100)",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        scId: null,
        customerId: null,
        salerId: null,
        saleOrderId: null,
        description: null,
        createBy: null,
        createTime: null,
        approveBy: null,
        approveTime: null,
        settleStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: [
          { required: true, message: "单据号不能为空", trigger: "blur" }
        ],
        scId: [
          { required: true, message: "仓库不能为空", trigger: "blur" }
        ],
        customerId: [
          { required: true, message: "客户不能为空", trigger: "blur" }
        ],
        totalNum: [
          { required: true, message: "商品数量不能为空", trigger: "blur" }
        ],
        totalGiftNum: [
          { required: true, message: "赠品数量不能为空", trigger: "blur" }
        ],
        totalAmount: [
          { required: true, message: "单据总金额不能为空", trigger: "blur" }
        ],
        createBy: [
          { required: true, message: "操作人不能为空", trigger: "blur" }
        ],
        createById: [
          { required: true, message: "创建人ID不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "操作时间不能为空", trigger: "blur" }
        ],
        updateBy: [
          { required: true, message: "修改人不能为空", trigger: "blur" }
        ],
        updateById: [
          { required: true, message: "修改人ID不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "修改时间不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
        settleStatus: [
          { required: true, message: "结算状态不能为空", trigger: "change" }
        ],
      },
      //拒绝原因
      refuseForm: {
        reason: ''
      },
      refuseRules: {
        reason: [
          { required: true, message: "拒绝原因不能为空", trigger: "blur" }
        ]
      },
      //商品库存记录的id列表
      stockLogList:[],
      //客户费用
      SettleFeeSheet:[],
      SettleFeeSheet2:[],
      customerSettleFeeSheetDetail:[],

      shopList: [], // 门店列表
      flag: true,
    };
  },
  created() {
    this.getList();
    this.getListId();
    this.selectStockLogList();
  },
  methods: {
    parseTime,
    /** 查询销售出库单列表 */
    getList() {
      this.loading = true;
      customer(this.customer).then(response => {
        this.customer = response.rows;
      });
      center({categoryType:1}).then(response => {
        this.ck = response.rows;
      });
      listUser(this.user).then(response => {
        this.user = response.rows;
      });
      this.queryParams.flag = null;
      listSheet(this.queryParams).then(response => {
        this.sheetList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      listShop().then(response => {
        this.shopList = response.rows;
      });
    },
    //商品库存变动记录
    selectStockLogList(){
      listLog({}).then(response => {
        let list = response.rows;
        for (let i = 0; i < list.length; i++) {
          this.stockLogList.push(list[i].id)
        }
      });
    },
    /** 查询客户费用单列表 */
    getListId() {
      this.SettleFeeSheet=[];
      var list=[];
      listCustomerSettleFeeSheet({}).then(response => {
        this.SettleFeeSheet2=response.rows;
        list=response.rows;
        for (var i=0;i<list.length;i++){
          this.SettleFeeSheet.push(list[i].id);
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 审核拒绝取消按钮
    statusCancel() {
      this.open2=false;
      this.open=true;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        scId: null,
        customerId: null,
        salerId: null,
        paymentDate: null,
        saleOrderId: null,
        totalNum: null,
        totalGiftNum: null,
        totalAmount: null,
        description: null,
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null,
        approveBy: null,
        approveTime: null,
        status: null,
        refuseReason: null,
        settleStatus: null,
        txId: null,
        oriSettleStatus: null
      };
      this.tblSaleOutSheetDetailList = [];
      this.resetForm("form");
    },
    // 查看按钮
    selectOrder(row){
      const id = row.id || this.ids
      getSheet(id).then(response => {
        this.form = response.data;
        this.tblSaleOutSheetDetailList = response.data.tblSaleOutSheetDetailList;
        //显示商品销售数量
        getOrder(this.form.saleOrderId).then(response => {
          for (let i = 0; i < response.data.tblSaleOrderDetailList.length; i++) {
            this.$set(
              this.tblSaleOutSheetDetailList[i],
              'saleOrderNum',
              response.data.tblSaleOrderDetailList[i].orderNum
            );
            this.selectProductStockList(this.form.scId, this.tblSaleOutSheetDetailList[i])
          }
          console.log(this.tblSaleOutSheetDetailList);
          this.open = true;
          this.title = "查看";
        });
      });

      if (row.status==0){
        this.statusColor = "rgb(100, 100, 100)";
      }else if (row.status==3){
        this.statusColor = "rgb(82, 196, 26)";
      }else {
        this.statusColor = "rgb(255, 0, 0)";
      }
    },
    //获取库存列表
    selectProductStockList(scId, tblSaleOutSheetDetail) {
      listStock({scId,productId:tblSaleOutSheetDetail.productId}).then(response => {
        tblSaleOutSheetDetail.baseDataProduct.tblProductStock = response.rows[0];
      });
    },
    //审批按钮
    statusUpdate(row){
      this.reset();

      const id = row.id || this.ids
      getSheet(id).then(response => {
        this.form = response.data;
        this.tblSaleOutSheetDetailList = response.data.tblSaleOutSheetDetailList;
        //显示商品销售数量
        getOrder(this.form.saleOrderId).then(response => {
          for (let i = 0; i < response.data.tblSaleOrderDetailList.length; i++) {
            this.$set(
              this.tblSaleOutSheetDetailList[i],
              'saleOrderNum',
              response.data.tblSaleOrderDetailList[i].orderNum
            );
            this.selectProductStockList(this.form.scId, this.tblSaleOutSheetDetailList[i])
          }
          console.log(this.tblSaleOutSheetDetailList);
        });
        this.open = true;
        this.title = "审批";
      });

      if (row.status==0){
        this.statusColor = "rgb(100, 100, 100)";
      }else if (row.status==3){
        this.statusColor = "rgb(82, 196, 26)";
      }else {
        this.statusColor = "rgb(255, 0, 0)";
      }
    },
    // 打印
    handlePrint(){
      window.print();
    },
    /** 审核通过、审核拒绝按钮 */
    async submitForm(status) {
      const response = await isDelivery(this.form.id);
      if (!response) {
        this.$modal.msgError("该销售出库单还未发货，无法审核");
        return; // 终止 submitForm 后续执行
      }
      for (var i = 0; i < this.tblSaleOutSheetDetailList.length; i++){
        if (this.tblSaleOutSheetDetailList[i].orderNum !== this.tblSaleOutSheetDetailList[i].saleOrderNum){
          this.$modal.msgError("第"+(i+1)+"行的销售出库数量与销售订单数量不一致")
          return false;
        }
      }
      if (status==6){
        this.open = false;
        this.refuseOpen=true
      }else {
        this.form.status=status;
        this.form.paymentDate = new Date();
        this.form.approveBy='系统管理员';
        this.form.approveTime=new Date();
        this.form.tblSaleOutSheetDetailList = this.tblSaleOutSheetDetailList;
        updateSheet(this.form).then(response => {
          if(response.code===200){
            //出库审核通过后添加商品库存记录
            for (let i = 0; i < this.form.tblSaleOutSheetDetailList.length; i++) {
              let stockNum = (this.form.tblSaleOutSheetDetailList[i].baseDataProduct.tblProductStock.stockNum - this.form.tblSaleOutSheetDetailList[i].orderNum) - this.form.tblSaleOutSheetDetailList[i].baseDataProduct.tblProductStock.stockNum;
              let taxAmount = (this.form.tblSaleOutSheetDetailList[i].baseDataProduct.tblProductStock.stockNum - this.form.tblSaleOutSheetDetailList[i].orderNum) * this.form.tblSaleOutSheetDetailList[i].taxPrice - this.form.tblSaleOutSheetDetailList[i].baseDataProduct.tblProductStock.stockNum * this.form.tblSaleOutSheetDetailList[i].baseDataProduct.tblProductStock.taxPrice;
              let stockLog = {
                id: generateUniqueId(this.stockLogList),
                scId: this.form.scId,
                productId: this.form.tblSaleOutSheetDetailList[i].productId,
                oriTaxPrice: this.form.tblSaleOutSheetDetailList[i].baseDataProduct.tblProductStock.taxPrice,
                curTaxPrice: this.form.tblSaleOutSheetDetailList[i].taxPrice,
                oriStockNum: this.form.tblSaleOutSheetDetailList[i].baseDataProduct.tblProductStock.stockNum,
                curStockNum: this.form.tblSaleOutSheetDetailList[i].baseDataProduct.tblProductStock.stockNum - this.form.tblSaleOutSheetDetailList[i].orderNum,
                stockNum: stockNum,
                taxAmount: taxAmount,
                createBy: '系统管理员',
                createById: '1',
                createTime: new Date(),
                bizCode: this.form.code,
                bizType: 3,
              }
              addLog(stockLog).then(response => {
              })
            }
            this.$modal.msgSuccess("审批成功");

            //新增一条客户费用信息
            const newId = generateUniqueId(this.SettleFeeSheet);
            const Code = getOrderCode(this.SettleFeeSheet2);
            let customerSettleFeeSheet = {
              id: newId,
              code: Code,
              customerId: this.form.customerId,
              totalAmount: this.form.totalAmount,
              sheetType: 1,
              status: 0,
              customerSettleFeeSheetDetailList:[{
                id: generateUniqueId(this.customerSettleFeeSheetDetail),
                orderId: this.form.id,
                sheetId: newId,
                amount: this.form.totalAmount,
              }],
            }
            addCustomerSettleFeeSheet(customerSettleFeeSheet).then(response => {
            });
          }else {
            this.$modal.msgError("审批拒绝")
          }
          this.open = false;
          this.getList();
        });
      }
    },
    //拒绝原因
    refuseSubmit() {
      this.$refs["refuseForm"].validate(valid => {
        if (valid) {
          this.form.status=6;
          this.form.approveBy='系统管理员';
          this.form.refuseReason=this.refuseForm.reason
          this.form.approveTime=new Date();
          updateSheet(this.form).then(response => {
            this.$modal.msgError("审批拒绝");
            this.open2 = false;
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据|
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();

      this.$router.push({
        path: '/orderOutSheet/add',
      })
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      const id = row.id

      // 判断是否已发货
      const response = await isDelivery(id);
      if (response) {
        this.$modal.msgError("该销售出库单已发货，无法修改");
        return;
      }

      this.reset();
      // eslint-disable-next-line require-await
      this.$router.push({
        path:'/orderOutSheet/update',
        query:{
          id: id,
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除销售出库单编号为"' + ids + '"的数据项？').then(function() {
        return delSheet(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 销售出库单序号 */
    rowTblSaleOutSheetDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 销售出库单添加按钮操作 */
    handleAddTblSaleOutSheetDetail() {
      let obj = {};
      obj.productId = "";
      obj.orderNum = "";
      obj.oriPrice = "";
      obj.taxPrice = "";
      obj.discountRate = "";
      obj.isGift = "";
      obj.taxRate = "";
      obj.description = "";
      obj.orderNo = "";
      obj.settleStatus = "";
      obj.saleOrderDetailId = "";
      obj.oriBundleDetailId = "";
      obj.returnNum = "";
      this.tblSaleOutSheetDetailList.push(obj);
    },
    /** 销售出库单删除按钮操作 */
    handleDeleteTblSaleOutSheetDetail() {
      if (this.checkedTblSaleOutSheetDetail.length == 0) {
        this.$modal.msgError("请先选择要删除的销售出库单数据");
      } else {
        const tblSaleOutSheetDetailList = this.tblSaleOutSheetDetailList;
        const checkedTblSaleOutSheetDetail = this.checkedTblSaleOutSheetDetail;
        this.tblSaleOutSheetDetailList = tblSaleOutSheetDetailList.filter(function(item) {
          return checkedTblSaleOutSheetDetail.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleTblSaleOutSheetDetailSelectionChange(selection) {
      this.checkedTblSaleOutSheetDetail = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/outsheet/export', {
        ...this.queryParams
      }, `sheet_${new Date().getTime()}.xlsx`)
    }
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      // 重新获取数据
      vm.getList();
    });
  }
};
// ID生成
function generateUniqueId(existingIds) {
  const prefix = '18';
  const length = 19 - prefix.length;
  const characters = '0123456789';
  let uniqueId;

  do {
    uniqueId = prefix;
    for (let i = 0; i < length; i++) {
      uniqueId += characters.charAt(Math.floor(Math.random() * characters.length));
    }
  } while (existingIds.includes(uniqueId));

  return uniqueId;
}
//单号生成
function getOrderCode(list) {
  var date = new Date(),
    year = date.getFullYear(),
    month = date.getMonth() + 1, // 月份是从0开始的
    day = date.getDate();

// 如果月份或日期是个位数，在前面补0
  month = month < 10 ? '0' + month : month;
  day = day < 10 ? '0' + day : day;

  var time=year + '' + month + '' + day

  let type="KHYSK"; //客户应收款
  var code=time+'0000000'
  var str1=code.slice(0,7)
  var str2=code.slice(7,)

  if (str2.slice(0,1)=="0"){
    str1=code.slice(0,6)
    str2=code.slice(6,)

    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(5,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(6,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(6,)
        }
      }
    }
  }else {
    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(5,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(7,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(7,)
        }
      }
    }
  }

  code=type+str1+(parseInt(str2)+1)

  return code.toString();
}
</script>
<style>
@media print {
  body > * {
    visibility: hidden;
  }
  #printableArea, #printableArea * {
    visibility: visible;
  }
  #printableArea {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
  }
}
</style>
